using System;
using System.Collections;
using System.Xml;
using Aggregator;

namespace CoffeeShopAggregator
{
	public class AggregateConcatenate : IAggregate
	{
        IList messages = new ArrayList();
        string numMessagesInAggregateXPath;
        string resultMessageRootElementName;
        int expectedNumberOfMessages = -1;

		public AggregateConcatenate(string numMessagesInAggregateXPath, string resultMessageRootElementName)
		{
            this.numMessagesInAggregateXPath = numMessagesInAggregateXPath;
            this.resultMessageRootElementName = resultMessageRootElementName;
        }

        public void AddMessage(XmlDocument message)
        {
            if (!IsComplete()) 
            {
                if (expectedNumberOfMessages == -1) 
                {
                    string val = GetNodeValue(message, numMessagesInAggregateXPath);
                    try 
                    {
                        expectedNumberOfMessages = Int32.Parse(val);
                    }
                    catch (Exception) {}
                }
                messages.Add(message);
            }
        }

        public bool IsComplete()
        {
            return (messages.Count == expectedNumberOfMessages);
        }

        public XmlDocument GetResultMessage()
        {
            XmlDocument result = new XmlDocument();
            result.LoadXml("<" + resultMessageRootElementName + "/>");
            foreach (XmlDocument message in messages)
            {
                try 
                {
                    result.DocumentElement.AppendChild(result.ImportNode(message.DocumentElement, true));
                }
                catch (Exception e) 
                {
                    Console.WriteLine(e.ToString());
                }
            }
            return result;
        }

        protected string GetNodeValue(XmlDocument doc, string path)
        {
            XmlNode node = doc.SelectSingleNode(path);
            if (node == null)
                return null;
            if (node is XmlAttribute) 
            {
                return node.Value;
            }
            else 
            {
                return node.InnerText;
            }
        }

    } 
}
